package wei.swing;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/***
 * 用于显示图片的控件
 */
public class PictureView extends JPanel {

    private Image image;

    private Color bgColor;

    public PictureView(){

    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // 设置白色背景
        int width = this.getWidth();
        int height = this.getHeight();
        if(bgColor != null){
            g.setColor(bgColor);
            g.fillRect(0, 0, width, height);
        }

        //
        if(true){
            g.setColor(Color.GRAY);
            g.drawRect(0, 0, width-1, height-1);
        }

        //
        if(image != null){
            int imgW = image.getWidth(null);
            int imgH = image.getHeight(null);

            // Rectangle 是一个纯数据类，记录坐标位置
            Rectangle rect = new Rectangle(0, 0, width, height);
            rect.grow(-2, -2);  // 收缩两个像素
            Rectangle fit = fitCenter(rect, imgW, imgH);
            g.drawImage(image, fit.x, fit.y, fit.width, fit.height, null);
        }

    }

    private Rectangle fitCenter(Rectangle rect, int imgW, int imgH){
        // 先尝试以窗口之宽度作为图片宽度，按比例绘制图片
        int fitW = rect.width;
        int fitH = rect.width * imgH / imgW;
        if(fitH > rect.height){
            fitH = rect.height;
            fitW = rect.height * imgW / imgH;
        }

        //
        int fitX = rect.x + (rect.width - fitW) / 2;
        int fitY = rect.y + (rect.height - fitH) / 2;
        return new Rectangle(fitX, fitY, fitW, fitH);
    }
    // 设置图片
    public void setImage(Image image){
        this.image = image;
        this.repaint();
    }

    public void setImage(File file){
        try {
            this.image = ImageIO.read(file);
            this.repaint();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setImage(String resourcePath){
        InputStream res = this.getClass().getResourceAsStream(resourcePath);
        try {
            this.image = ImageIO.read(res);
            this.repaint();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 设置背景颜色
    public void setBackgroundColor(Color color){
        this.bgColor = color;
        this.repaint();     // 重新绘制
    }

}
